import mysql.connector
from mysql.connector import pooling
import streamlit as st

# 从Streamlit的secrets中获取数据库配置
db_config = {
    'host': st.secrets["mysql"]["host"],
    'user': st.secrets["mysql"]["user"],
    'password': st.secrets["mysql"]["password"],
    'database': st.secrets["mysql"]["database"],
    'use_pure': True  # 使用纯Python实现以获得更明确的错误信息
}
try:
    # 创建数据库连接池
    cnx_pool = pooling.MySQLConnectionPool(pool_name="bank_pool",
                                           pool_size=5,
                                           **db_config)
    print("数据库连接池创建成功")

except mysql.connector.Error as err:
    print(f"数据库连接失败: {err}")
    st.error(f"数据库连接失败: {err}")
    cnx_pool = None

def get_connection():
    """从连接池中获取一个数据库连接"""
    if cnx_pool:
        try:
            return cnx_pool.get_connection()
        except mysql.connector.Error as err:
            st.error(f"获取数据库连接失败: {err}")
            return None
    st.error("数据库连接池未初始化")
    return None 